from django.shortcuts import render_to_response
from music.models import *
from django.template import loader, Context, RequestContext
from django import http
from django.http import HttpResponse
from django.template.loader import get_template
import cStringIO as StringIO
import cgi
from django.core.mail import send_mail
from django.utils.encoding import smart_unicode, force_unicode, smart_str

def album_list(request):
    albums = Album.objects.filter(publish=1).select_related().order_by('album_category__order','-date')
    songs = Song.objects.all().order_by('-album__date')
    context = "music"
    return render_to_response('music/album_list.html', {'albums':albums, 'context':context}, context_instance=RequestContext(request))

def album_detail(request, album_id):
    album = Album.objects.get(id = album_id)
    songs = Song.objects.filter(album = album_id).order_by('track_number')
    context = "music"
    return render_to_response('music/album_detail.html', {'album':album, 'songs':songs, 'context':context}, context_instance=RequestContext(request))

def playlist(request):
    songs = Song.objects.select_related().order_by('-album__date', 'track_number')
    return render_to_response('music/playlist.html', {'songs':songs}, context_instance=RequestContext(request), mimetype='application/xspf+xml')

def player(request):
    return render_to_response('music/player.html', context_instance=RequestContext(request))
    
import urllib2, urllib

def song_detail(request, song_id):
    song = Song.objects.get(id = song_id)
    context = "music"
    return render_to_response('music/song_detail.html', {'song':song, 'context':context}, context_instance=RequestContext(request))

def song_download(request, song_id):
    song = Song.objects.get(id = song_id)
    send_mail('donwload %s' % (smart_unicode(song.title)), '', 'contact@sam-lesite.fr',['samusic@free.fr'], fail_silently=False)
    response = HttpResponse(urllib2.urlopen(song.soundfile))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = "attachment; filename=\"%s.mp3\"" % (smart_str(song.title))
    return response
    
def url_download(request, url):
    filename = url.split('/')[-1].split('#')[0].split('?')[0]
    send_mail('donwload %s' % (smart_unicode(filename)), '', 'contact@sam-lesite.fr',['samusic@free.fr'], fail_silently=False)
    response = HttpResponse(urllib.urlopen(url))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = "attachment; filename=\"%s\"" % (smart_str(filename))
    return response    

def song_remix(request, song_id):
    song = Song.objects.get(id = song_id)    
    context = "music"
    return render_to_response('music/song_remix.html', {'song':song, 'context':context}, context_instance=RequestContext(request))